<?php

namespace App\Api\Controllers;

 use App\Http\Controllers\Controller; 
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use App\Api\Services\SealManageService;
use App\Api\Models\SealManageModel;
use App\Helper\Utils\CircleSeal;
use App\Http\Controllers\Api\BaseController;
class SealManageController extends BaseController
{
    /**
     * 添加印章
     */
    public function add(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'seal_name'    => 'required|string',//印章名称
            'temp_id'      => 'string',//印章模板id
            'company_name' => 'required|string',//公司名称     
           
        ],[
            'seal_name.required'   =>"印章名称，不能为空！",
            'company_name.required'=>"公司名称，不能为空！"            
        ]);
    
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }        
        ob_end_clean();      
        $name = $data['company_name'];
        $path ='uploads/yz/' . date("Y") . "-" . date("m") . "-". date("d").'/';
        @mkdir($path,0755,true);
        $filename = uniqid();
        $picpath = $path .$filename;
      
        $cc = new CircleSeal($name);             
        $sealname = $data['seal_name'];
        $cc->saveImg($picpath.".jpg",$sealname);       
        //开启事务
       DB::beginTransaction();       
        try{
            //印章
            $dData = $data;
            $dData['created_at']   = time();
            $dData['seal_img']     = '/'.$picpath.".jpg";
            $dData['user_id']      = $this->getUserId();
            $dData['main_id']      = $this->getMainUserId();            
            SealManageService::add($dData);            
            DB::commit();//提交事务
            return $this->success();
        }catch (Exception $e){
            DB::rollBack();//事务回滚
            //异常响应
            return $this->fail($e->getMessage(),'添加印章');
        }
         
    }
    
    /**
     * 删除印章信息
     * @param ids (删除多个逗号分隔)
     */
    public function delete(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'ids'       =>'required',//印章id
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg'  => $info,
                'data' => '',
            ]);
        }
        
        $id_data = [];
        $id_arr  = explode(',',$data['ids']);
        
        $condition['user_id'] = $this->getUserId();
        $condition['main_id'] = $this->getMainUserId();
        
        $list = SealManageModel::select('id','seal_img')->where($condition)->whereIn('id',$id_arr)->get()->toArray();
        
        if(!empty($list)){
            
            foreach ($list as $k=>$v){
                
                $id_data[]=$v['id'];
                
                if(is_file(public_path($v['seal_img']))){
                    
                    unlink(public_path($v['seal_img']));
                }
            }
            
            $bool = SealManageModel::where($condition)->whereIn('id',$id_data)->delete();;
             
            if($bool){
                
                return $this->success();
                 
            }else{
                return $this->fail('','删除失败');
            }
        }
        return $this->fail('','此印章，不存在！');
    }
    
    /**
     * 修改印章
     *
     */
    public function update(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'seal_id' =>'required|integer',//印章id
            'seal_name'      => 'required|string',//印章名称
            'temp_id'       => 'string',//印章模板id
            'company_name'  => 'required|string',//公司名称     

        ]);
    
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        
        $info = SealManageService::getSealManageInfo(['id'=> $data['seal_id']]);
         
        if(empty($info)){
             
            return $this->fail('','此印章,不存在！');
        }
        if($data['company_name'] != $info['company_name'] || $data['seal_name'] != $info['seal_name']){
            
            ob_end_clean();
            $name = $data['company_name'];
            $path ='uploads/yz/' . date("Y") . "-" . date("m") . "-". date("d").'/';
            @mkdir($path,0755,true);
            $filename = uniqid();
            $picpath = $path .$filename;
            
            $cc = new CircleSeal($name);
            $sealname = $data['seal_name'];
            $cc->saveImg($picpath.".jpg",$sealname);
            
            $data['seal_img']     = '/'.$picpath.".jpg";
        }
        //开启事务
        DB::beginTransaction();
        try{
            //印章
            $updData = $data;
            
            $condition['user_id'] = $this->getUserId();
            $condition['main_id'] = $this->getMainUserId();
            $condition['id']      = $updData['seal_id'];
            
            unset($updData['seal_id']);
            $updData['updated_at'] = time();
            
            $bool = SealManageService::update($condition,$updData);
            if($bool){
                
                if(is_file(public_path($info['seal_img']))){
                
                    unlink(public_path($info['seal_img']));
                } 
            }
            DB::commit();//提交事务
            return $this->success();
        }catch (Exception $e){
            DB::rollBack();//事务回滚
            //异常响应
            return $this->fail($e->getMessage(),'修改印章');
        }
    
    }
    
    /**
     * 印章信息
     * @param seal_id
     */
    public function find(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'seal_id'       =>'required|integer',//印章id
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg'  => $info,
                'data' => '',
            ]);
        }
    
        $condition['id']      = $data['seal_id'];
        $condition['user_id'] = $this->getUserId();
        $condition['main_id'] = $this->getMainUserId();
    
        $info = SealManageService::getSealManageInfo($condition);
           
        return $this->success($info);
    }
    
    /**
     * 印章列表
     */
    public function sealList(Request $request){    
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' =>'required|integer',//页面大小
            'currentPage' =>'required|integer',//当前页
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        
        $id_arr = [];
        $seal_id_arr = [];

        $condition['user_id'] = $this->getUserId();
        $condition['main_id'] = $this->getMainUserId();

        $list = SealManageService::getList($condition,$seal_id_arr,$data['pageSize'],$data['currentPage']);
    
       
        return $this->success($list);
    
    }
   
}
